<template>
  <el-dialog :title="!formData.id?'添加房产':'编辑房产'" :visible="showDialog" width="60%" @close="closeFn">
    <!-- 表单 -->
    <el-form ref="perForm" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="经纪">
        <!-- <el-select v-model="formData.agent"> -->
        <el-select v-model="formData.agent" placeholder="全部经纪">
          <el-option v-for="item in broker" :key="item.id" :value="item.id" :label="item.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="分类">
        <!-- <el-select v-model="formData.category"> -->
        <el-select v-model="formData.category" placeholder="全部分类">
          <el-option v-for="item in classify" :key="item.id" :value="item.id" :label="item.title" />
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="标签">
        <el-tag
          v-for="(item,index) in formData.tags"
          :key="index"
          closable
          @close="handleClose(item)"
        >
          {{ item }}
        </el-tag>
        <el-input
          v-if="inputVisible"
          ref="saveTagInput"
          v-model="inputValue"
          class="input-new-tag"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        />
        <el-button size="small" @click="showInput">+ 新标签</el-button>
      </el-form-item>
      <el-form-item label="地址">
        <el-cascader
          :options="options"
          placeholder="选择区域"
          @change="selectFn"
        />
        <el-input v-model="formData.address" placeholder="请输入地址" />
      </el-form-item>
      <el-form-item label="价格">
        <el-input v-model="formData.price" placeholder="请输入价格" />
      </el-form-item>
      <el-form-item label="描述" prop="desc">
        <el-input
          v-model="formData.desc"
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 3}"
          placeholder="请添加描述"
        />
      </el-form-item>
      <el-form-item label="内容" />
      <el-form-item v-model="formData.photos" label="介绍图片">
        <!-- 上传图片组件 -->
        <updateImage ref="houseUpdats" :limit="3" />
      </el-form-item>
      <el-form-item v-model="formData.image" label="封面">
        <!-- 上传图片组件 -->
        <updateImage ref="houseUpdat" />
      </el-form-item>
      <el-row type="flex" justify="end">
        <el-button size="small" @click="closeFn">取消</el-button>
        <el-button type="primary" size="small" @click="confirmFn">确定</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<script>
import { getClassify, addHouse, getAssignHouse, editHouse } from '@/api/house'
import { getAgentsList } from '@/api/agents.js'
import updateImage from '@/components/updateImage/index.vue'
import axios from 'axios'
export default {
  components: { updateImage },
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    id: {
      type: [String, Number],
      default: null
    }
  },
  data() {
    return {
      formData: {
        title: '', // 标题
        desc: '', // 描述
        image: '', // 图片
        agent: '', // 经纪id值
        content: '', // 内容
        address: '', // 地址
        price: '', // 价格
        photos: [], // 图片（url数组）
        tags: [], // 标签
        category: '' // 分类id值
      },
      rules: { // 校验规则
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        desc: [{ required: true, message: '描述不能为空', trigger: 'blur' }]
      },
      broker: '', // 经纪人
      options: [], // 地图
      classify: '', // 分类
      inputVisible: false, // 标签上的input默认不显示
      inputValue: '' // 标签上input的值
    }
  },
  async created() {
    const res = await getAgentsList() // 经纪人
    this.broker = res
    const result = await getClassify() // 分类
    console.log(result)
    this.classify = result
    // 地址获取
    const address = await axios({
      url: 'https://restapi.amap.com/v3/config/district?key=b7e2ace498ea8a3102c37fde6d9e7d08&subdistrict=3',
      method: 'get'
    })
    const data = address.data.districts[0].districts
    this.options = this.fun(data)
    console.log(this.formData.category)
  },
  methods: {
    // 确定事件
    async confirmFn() {
      // 校验表单
      await this.$refs.perForm.validate()
      // 调用接口实现新增/编辑
      if (!this.formData.id) {
        // 实现封面的新增
        this.formData.image = this.$refs.houseUpdat.imageUrl
        // 实现图片的新增
        const arr = []
        this.$refs.houseUpdats.fileList.forEach(item => {
          arr.push(item.url)
        })
        this.formData.photos.push(...arr)
        // 实现新增
        await addHouse(this.formData)
        console.log(this.formData)
      } else {
        // 实现封面的修改
        // this.formData.image = this.$refs.houseUpdat.imageUrl
        this.$refs.houseUpdat.fileList.forEach(item => {
          this.formData.image = item.url || ''
        })
        // 实现图片的修改
        const arr = []
        this.$refs.houseUpdats.fileList.forEach(item => {
          arr.push(item.url)
        })
        // 没有数据的时候，给个空数组
        if (!this.formData.photos) {
          this.formData.photos = []
        }
        this.formData.photos = [...arr]
        // 实现编辑
        await editHouse(this.formData)
      }
      // 关闭弹窗
      this.closeFn()
      // 重新获取列表
      this.$parent.getHouseLists()
    },
    // 获取指定房产(编辑)
    async getAssignHouse() {
      // 通过接口传递id拿到对应数据
      const res = await getAssignHouse(this.id)
      console.log(178, res)
      console.log(179, res.category.title)
      console.log(180, res.agent.name)
      // 重新赋值
      this.formData = res
      // if (res.category.title) {
      //   this.formData.category = res.category.title // 分类
      // }
      // if (res.agent.name) {
      //   this.formData.agent = res.agent.name // 经纪
      // }
      // this.formData.category.title = (res.category || res.category.title || null) // 分类
      // this.formData.agent.name = (res.agent || res.agent.name || null) // 经纪
      // console.log(191, this.formData.category.title)
      // console.log(192, this.formData.agent.name)
      // 封面回显
      if (this.formData.image) {
        this.$refs.houseUpdat.fileList.push({
          url: this.formData.image
        })
      }
      // 没有数据的时候，给个空数组
      if (!this.formData.photos) {
        this.formData.photos = []
      }
      // 图片回显
      this.formData.photos.forEach(item => {
        this.$refs.houseUpdats.fileList.push({ url: item })
      })
    },
    // 关闭弹窗时触发
    closeFn() {
      // 清空表单内容
      this.formData = {
        title: '', // 标题
        desc: '', // 描述
        image: '', // 图片
        agent: '', // 经纪id值
        content: '', // 内容
        address: '', // 地址
        price: '', // 价格
        photos: [], // 图片（url数组）
        tags: [], // 标签
        category: '' // 分类id值
      }
      // 清空图片组件中的数组
      this.$refs.houseUpdat.fileList = []
      this.$refs.houseUpdats.fileList = []
      // 清空校验规则
      this.$refs.perForm.resetFields()
      // 关闭弹窗
      this.$emit('update:showDialog', false)
    },
    // 关闭标签触发的事件
    handleClose(item) {
      this.formData.tags.splice(this.formData.tags.indexOf(item), 1)
    },
    // 标签上显示的input
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 标签上input失焦与键盘回车触发的事件
    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.formData.tags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    // 地址
    fun(data) {
      const arr = []
      data.forEach(item => {
        const obj = { value: item.name, label: item.name }
        if (item.districts.length > 0) {
          obj.children = this.fun(item.districts)
        }
        arr.push(obj)
      })
      return arr
    },
    // 地址发生变化时触发的函数
    selectFn(value) {
      const res = value.join(',')
      this.formData.address = res
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-form-item__content {
  display: flex;
}
.el-tag + .el-tag {
    margin-left: 10px;
  }
.button-new-tag {
    margin-left: 10px;
 }
 ::v-deep .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
